<template>
	<div class="app-container">
		<div ref="box3" class="flex-center margin-bottom-10">
			<el-radio-group v-model="searchParams.serviceState" size="medium" class="item-gap" @change="onStateChange">
				<el-radio-button v-for="item in auditStateList" :key="item.id" :label="item.id">
					<el-badge v-if="item.id <= 1 && item.count > 0" :value="item.count" :max="99">
						<span class="margin-right-20">{{ item.name }}</span>
					</el-badge>
					<div v-else class="margin-right-10" style="padding-bottom: 2px;">{{ item.name }}</div>
				</el-radio-button>
			</el-radio-group>
		</div>
		<jk-operation-card ref="box1" class="margin-bottom-10">
			<div class="flex-between-center-wrap">
				<div class="flex-start-center-wrap">
					<jk-button class="item-gap" size="small" type="warning" icon="el-icon-files" :disabled="!checkData || !checkData.length" @click="onBatchSetBtn">批量设定</jk-button>
					<jk-button class="item-gap" :disabled="!checkData || !checkData.length" icon="el-icon-printer" @click="onPrintBtn">打印</jk-button>
					<jk-button v-if="searchParams.serviceState === 1" :disabled="!checkData || !checkData.length" icon="el-icon-upload2" type="primary" size="small" @click="onReportBtn">导出</jk-button>
				</div>
				<div class="flex-end-center-wrap">
					<jk-select
						v-model="searchParams.workshopId"
						:option-list="workshopList"
						placeholder="区域"
						clearable
						size="small"
						class="search-bar-item-size1 margin-5-0 item-gap"
						@change="getProcessListByWorkshop"
					></jk-select>
					<jk-select
						v-model="searchParams.processCode"
						value-key-name="code"
						:option-list="processList"
						placeholder="工序"
						clearable
						size="small"
						class="search-bar-item-size1 margin-5-0 item-gap"
					></jk-select>
					<jk-search-input
						v-model="searchParams.productName"
						placeholder="品种名称"
						size="small"
						class="search-bar-item-size2 margin-5-0 item-gap"
						clearable
						@on-enter="onSearchBtn"
					/>
					<jk-search-input
						v-model="searchParams.batchCode"
						placeholder="批号"
						size="small"
						class="search-bar-item-size2 margin-5-0 item-gap"
						clearable
						@on-enter="onSearchBtn"
					/>
					<jk-search-input
						v-model="searchParams.machineName"
						placeholder="机台名称"
						size="small"
						class="search-bar-item-size2 margin-5-0 item-gap"
						clearable
						@on-enter="onSearchBtn"
					/>
					<jk-search-button @click="onSearchBtn"></jk-search-button>
					<!--<jk-more-search width="560" @on-confirm="onSearchBtn" @on-reset="onResetSearchBtn">
						<el-row :gutter="16" class="flex-start-center-wrap">
							<el-col :span="12">
								<jk-date-picker v-model="moreSearchParams.belongDate" type="daterange" size="small" class="margin-5-0 width-100-percent" start-placeholder="翻改开始日期" end-placeholder="翻改结束日期" clearable />
							</el-col>
							&lt;!&ndash;<el-col :span="12">
								<jk-search-input v-model="moreSearchParams.productOrderCode" placeholder="销售订单号" size="small" class="width-100-percent margin-5-0" clearable @on-enter="onSearchBtn" />
							</el-col>&ndash;&gt;
						</el-row>
					</jk-more-search>-->
				</div>
			</div>
		</jk-operation-card>

		<jk-card>
			<jk-table :loading="tableLoading" :data="tableData" :height="tableHeight + 10" @checkbox-change="onCheckboxChange">
				<vxe-table-column fixed="left" type="checkbox" width="60" align="center"></vxe-table-column>
				<vxe-column
					v-for="(item, index) in tableColumnList"
					:key="index"
					:title="item.title"
					:align="item.align"
					:field="item.keyName"
					:sortable="item.sortable"
					:fixed="item.fixed ? item.fixed : ''"
					:min-width="item.minWidth"
					:width="item.width"
				>
					<template slot-scope="scope">
						<jk-state-bar v-if="item.keyName === 'serviceState'" :state-list="auditStateList" :state="scope.row.serviceState"></jk-state-bar>
						<span v-else-if="item.keyName === 'paperTubeList'">{{ scope.row.paperTubeList && scope.row.paperTubeList.length ? scope.row.paperTubeList.map(x => x.name).join(',') : '' }}</span>
						<span v-else-if="item.keyName === 'ifTest'">{{ scope.row.ifTest ? '试产打样' : '正式生产' }}</span>
						<span v-else-if="item.keyName === 'waistPopeList'">{{ scope.row.waistPopeList && scope.row.waistPopeList.length ? scope.row.waistPopeList.map(x => x.name).join(',') : '' }}</span>
						<span v-else-if="item.keyName === 'labelColorList'">{{ scope.row.labelColorList && scope.row.labelColorList.length ? scope.row.labelColorList.map(x => x.name).join(',') : '' }}</span>
						<span v-else-if="item.keyName === 'batchOneList'">{{ transferSpec(scope.row.batchOneList || []) }}</span>
						<!--						<span v-else-if="item.keyName === 'specSheet'">{{ scope.row.specSheet ? scope.row.specSheet.code : '' }}</span>-->
						<div v-else-if="item.keyName === 'specSheet'" class="flex-start-center">
							<task-list :data-list="scope.row.specSheet && scope.row.specSheet.specSheetParamList && scope.row.specSheet.specSheetParamList.length ? scope.row.specSheet.specSheetParamList : null"></task-list>
						</div>
						<span v-else>{{ scope.row[item.keyName] }}</span>
					</template>
				</vxe-column>
				<vxe-column title="操作" align="center" fixed="right" :width="180">
					<template slot-scope="scope">
						<div class="flex-center">
							<jk-button size="mini" type="primary" class="item-gap" :disabled="scope.row.serviceState !== 0" @click="onEditBtn(scope.row)">录入工艺</jk-button>
							<el-dropdown trigger="click" @command="onDropdownChange($event, scope.row)">
								<el-button type="primary" size="mini" class="el-dropdown-link">
									更多<i class="el-icon-arrow-down el-icon--right"></i>
								</el-button>
								<el-dropdown-menu slot="dropdown">
									<el-dropdown-item
										v-for="(item) in dropdownOption"
										:key="item.code"
										:command="item.code"
										:divided="item.divided"
										:disabled="item.allowState || item.allowState === 0 ? scope.row.serviceState !== item.allowState : false"
										:style="{
											'display': !item.isShow ? 'none' : 'block',
											'text-decoration': getPermission([`${prefix}:${item.permissionName}`]) ? '' : 'line-through'
										}"
									>
										<span :class="`${item.icon} item-gap`"></span>
										<span>{{ item.name }}</span>
									</el-dropdown-item>
								</el-dropdown-menu>
							</el-dropdown>
						</div>
					</template>
				</vxe-column>
			</jk-table>
			<!-- 分页组件 -->
			<footer ref="box2" class="flex-end-center margin-top-10">
				<jk-page
					:page-index="searchParams.pageNo"
					:page-sizes="searchParams.pageSizes"
					:page-size="searchParams.pageSize"
					:total="totalCount"
					@on-change="onPageChange"
				/>
			</footer>
		</jk-card>
		<save-dialog
			:data-item="dataItem"
			:dialog-state="saveDialogState"
			@on-visible-change="onVisibleChange"
			@on-finish="onFinish"
		></save-dialog>
		<batch-save-dialog
			:check-data="checkData"
			:dialog-state="batchSaveDialogState"
			@on-visible-change="onVisibleChangeOfBatchSaveDialog"
			@on-finish="onFinishOfBatchSaveDialog"
		></batch-save-dialog>
		<machine-technology-detail-dialog
			:data-item="dataItem"
			:dialog-state="technologyDetailDialogState"
			@on-visible-change="onVisibleChangeOfTechnologyDetailDialog"
		></machine-technology-detail-dialog>
	</div>
</template>

<script>
    import saveDialog from './save-dialog';
    import batchSaveDialog from './batch-save-dialog';
    import calHeight from '/src/mixins/cal-table-height';
    import taskList from './components/task-list';
    import { formatDate, pageConfig, tipsBar } from '/src/utils/jk/jk-tool';
    import {
        productionTechnologySettingsGetStateCount, getFixedJson,
        productionTechnologySettingsPage, productionTechnologySettingsUpdateServiceState
    } from '@/api/technology/technologySet';
    import getMenuColumn from '../../../mixins/getMenuColumn';
    import permissionMixin from '../../../mixins/permission-mixin';
    import machineTechnologyDetailDialog from './detail-dialog';
    import filterProcessList from '../../../mixins/filter-process-list';

    export default {
        name: 'TechnologySet',
        components: {
            machineTechnologyDetailDialog,
            batchSaveDialog,
            saveDialog,
            taskList
        },
        mixins: [calHeight, getMenuColumn, permissionMixin, filterProcessList],
        data() {
            return {
                apiItem: {
                    'page': productionTechnologySettingsPage,
                    'export': getFixedJson
                },
                technologyDetailDialogState: false,
                batchSaveDialogState: false,
                prefix: 'production:technologySettings',
                auditStateList: [
                    { id: 0, name: '待设定', color: '#808695' },
                    { id: 1, name: '已设定', color: '#2d8cf0' },
                    { id: 2, name: '忽略', color: '#19be6b' }
                ],
                dropdownOption: [
                    { code: 'QUERY', name: '详情', isShow: true, permissionName: 'query', divided: false, icon: 'el-icon-view', allowState: null, api: null },
                    { code: 'SET', name: '标为设定', isShow: true, permissionName: 'update', divided: true, icon: 'el-icon-s-flag', allowState: 0, state: 1, api: productionTechnologySettingsUpdateServiceState },
                    { code: 'CANCEL_SET', name: '撤销设定', isShow: true, permissionName: 'update', divided: false, icon: 'el-icon-top-left', allowState: 1, state: 0, api: productionTechnologySettingsUpdateServiceState },
                    { code: 'IGNORE', name: '忽略', permissionName: 'update', isShow: true, icon: 'el-icon-brush', allowState: 0, state: 2, api: productionTechnologySettingsUpdateServiceState },
                    { code: 'CANCEL_IGNORE', name: '撤销忽略', permissionName: 'update', isShow: true, icon: 'el-icon-circle-close', allowState: 2, state: 0, api: productionTechnologySettingsUpdateServiceState }
                ],
                dataItem: {},
                workshopList: [],
                saveDialogState: false,
                tableLoading: true,
                exportLoading: false,
                tableData: [],
                totalCount: 0,
                processList: [],
                searchParams: {
                    pageNo: pageConfig.pageNo,
                    pageSize: pageConfig.pageSize,
                    workshopId: null,
                    processCode: '',
                    machineName: '',
                    productName: '',
                    batchCode: '',
                    serviceState: 0
                },
                checkData: [],
                moreSearchParams: {
                    belongDate: [],
                    productOrderCode: ''
                }
            };
        },
        methods: {
            // 生成 CSV 字符串
            generateCSV(jsonData) {
                const header = jsonData.tableHeader.map(header => header.value).join(',');
                const rows = jsonData.tableData.map(row => {
                    return jsonData.tableHeader.map(header => row[header.key] || '').join(',');
                });

                return [header, ...rows].join('\n');
            },
            /** 导出按钮操作 */
            onReportBtn() {
                const params = { ...this.searchParams, ids: this.checkData.map(x => x.id).join(',') };
                this.$modal.confirm('是否确认导出所有数据数据项?').then(() => {
                    this.exportLoading = true;
                    return this.apiItem['export'](params);
                }).then(res => {
                    console.log(JSON.stringify(res.data.res), 'res');
                    const { tableData, tableHeader } = res.data.res;
                    if (res.data.status === 200) {
                        import('@/vendor/Export2Excel').then(excel => {
                            const tHeader = tableHeader.map(header => header.value);
                            const filterVal = tableHeader.map(header => header.key);
                            const data = tableData.map(v => filterVal.map(j => {
                                return v[j];
                            }));
                            excel.export_json_to_excel({
                                header: tHeader,
                                data,
                                filename: `工艺设定已设定的机台记录`,
                                autoWidth: true,
                                bookType: 'xls'
                            });
                        });
                    }
                }).catch(() => {});
            },
            // 工艺去重
            transferSpec(e) {
                let arr = new Set(e || []);
                arr = Array.from(arr);
                const str = arr.map(x => x).join(',');
                return str || '无';
            },
            onVisibleChangeOfTechnologyDetailDialog(e) {
                this.technologyDetailDialogState = e;
            },
            onFinishOfBatchSaveDialog() {
                this.getListRequest();
                this.batchSaveDialogState = false;
            },
            onVisibleChangeOfBatchSaveDialog(e) {
                this.batchSaveDialogState = e;
            },
            onBatchSetBtn() {
                if (this.validatorCheckData()) {
                    tipsBar(this, 'custom', 'warning', `只能批量操作相同品种和批号的机台!`);
                } else {
                    this.batchSaveDialogState = true;
                }
            },
            onResetSearchBtn() {
                Object.assign(this.$data.moreSearchParams, this.$options.data().moreSearchParams);
            },
            onCheckboxChange(e) {
                this.checkData = e.records;
                // if (this.validatorCheckData()) {
                //     tipsBar(this, 'custom', 'warning', `只能批量操作相同品种和批号的机台!`);
                // }
            },
            validatorCheckData() {
                let products = this.checkData.map(x => x.productName);
                products = Array.from(new Set(products));

                let batchList = this.checkData.map(x => x.batchCode);
                batchList = Array.from(new Set(batchList));

                return products.length > 1 || batchList.length > 1;
            },
            onPrintBtn() {
                const routeUrl = this.$router.resolve({
                    name: 'printTechnology',
                    query: {
                        ids: this.checkData.map(x => x.id).join(',')
                    }
                });
                window.open(routeUrl.href, '_blank');
            },
            onDropdownChange(type, row) {
                const optionItem = this.dropdownOption.find(x => x.code === type);
                if (this.getPermission([`${this.prefix}:${optionItem.permissionName}`])) {
                    if (optionItem) {
                        if (optionItem.code === 'QUERY') {
                            this.onDetailBtn(row);
                        } else {
                            this.$confirm(`确定"${optionItem.name}"吗？`, '提示', { type: 'warning' }).then(() => {
                                optionItem.api({ id: row.id, state: optionItem.state }).then(res => {
                                    if (res.data.status === 200) {
                                        this.getListRequest();
                                    }
                                });
                            }).catch(() => {});
                        }
                    }
                } else {
                    tipsBar(this, 'custom', 'warning', '无操作权限!');
                }
            },
            onStateChange() {
                this.$set(this.searchParams, 'pageNo', 1);
                this.getListRequest();
            },
            onSearchBtn() {
                this.$set(this.searchParams, 'pageNo', 1);
                this.getListRequest();
            },
            onPageChange(e, size) {
                this.$set(this.searchParams, 'pageNo', e);
                this.$set(this.searchParams, 'pageSize', size);
                this.getListRequest();
            },
            async getDependentData() {
                this.tableLoading = true;
                this.workshopList = this.$store.state.user.userWorkshop.workshopList || [];
                /* if (!this.searchParams.belongDate) {
                    this.$set(this.searchParams, 'belongDate', formatDate(Date.now()));
                }*/
                if (!this.searchParams.workshopId) {
                    this.$set(this.searchParams, 'workshopId', this.$store.state.user.userWorkshop.defaultWorkshopId);
                }
                /* if (!this.searchParams.processId) {
            this.$set(this.searchParams, 'processId', this.$store.state.user.userProcess.defaultProcessId);
        }*/
                this.getProcessListByWorkshop();
                await this.getMenuColumnListRequest();
                await this.getListRequest();
                this.tableLoading = false;
            },
            onDetailBtn(e) {
                this.dataItem = e;
                this.technologyDetailDialogState = true;
            },
            onFinish() {
                this.saveDialogState = false;
                this.getListRequest();
            },
            onVisibleChange(e) {
                this.saveDialogState = e;
                if (!e) {
                    this.dataItem = {};
                }
            },
            getStateBarCountRequest() {
                return productionTechnologySettingsGetStateCount(this.searchParams).then(res => {
                    if (res.data.status === 200) {
                        this.auditStateList = this.auditStateList.map(x => {
                            x.count = 0;
                            res.data.res.forEach(k => {
                                if (x.id === k.auditState) {
                                    x.count = k.count;
                                }
                            });
                            return x;
                        });
                    } else {
                        this.auditStateList = this.auditStateList.map(x => {
                            x.count = 0;
                            return x;
                        });
                    }
                });
            },
            /** 查询列表 */
            getListRequest() {
                this.tableLoading = true;
                this.checkData = [];
                return this.apiItem['page'](this.searchParams).then(res => {
                    this.getStateBarCountRequest();
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        this.tableData = res.data.res;
                        this.totalCount = res.data.count;
                    }
                });
            },
            /** 新增按钮操作 */
            onAddBtn() {
                this.saveDialogState = true;
            },
            /** 修改按钮操作 */
            onEditBtn(row) {
                this.dataItem = row;
                this.saveDialogState = true;
            }
        },
        mounted() {
            this.getDependentData();
        }
    };
</script>
